package vg.modules.opener.decoders.graphml;

import vg.modules.opener.decoders.IDecoder;
import vg.interfaces.ll_services.data_base_service.IGraphDataBaseService;
import vg.services.main_manager.VGMainServiceHelper;
import vg.services.progress_manager.interfaces.IProgressTask;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * GraphML decoder.
 *
 * @author Timur Zolotuhin (e-mail: tzolotuhin@gmail.com)
 */
public class GraphMLDecoder implements IDecoder {
    @Override
    public List<Integer> decode(File file, IGraphDataBaseService graphDataBase, String graphName) throws Exception {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            GraphMLParser handler = new GraphMLParser(graphDataBase, graphName);
            final long fileSize = (int)file.length();
            final FileInputStream fis = new FileInputStream(file);

            IProgressTask task = new IProgressTask() {
                @Override
                public long getValue() {
                    if (fis.getChannel() != null)
                        try {
                            System.out.println(fis.getChannel().position() + "/" + fileSize);
                            return fis.getChannel().position();
                        } catch (IOException ex) {
                            VGMainServiceHelper.logger.printException(ex);
                        }
                    return getLength();
                }

                @Override
                public long getLength() {
                    return fileSize;
                }

                @Override
                public String getTaskName() {
                    return "Open graphML file";
                }
            };

            VGMainServiceHelper.progressManager.addTask(task);

            saxParser.parse(fis, handler);
            VGMainServiceHelper.progressManager.removeTask(task);

            List<Integer> graphModelIds = new ArrayList<>();
            graphModelIds.add(handler.getGraphModelId());

            return graphModelIds;
        } catch (Exception ex) {
            VGMainServiceHelper.logger.printException(ex);
            throw ex;
        }
    }
}
